package com.hoshiicloud.goods.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.goods.entity.spu.ExtSpuTags;
import com.hoshiicloud.goods.param.spu.ExtSpuTagsAddParam;
import com.hoshiicloud.goods.param.spu.ExtSpuTagsQueryParam;
import com.hoshiicloud.goods.param.spu.ExtSpuTagsUpdateParam;
import com.hoshiicloud.goods.service.ExtSpuTagsService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * SPU服务标签 控制器
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/goods/ext-spu-tags")
@Api(value = "SPU服务", tags = {"SPU服务"})
public class ExtSpuTagsController {
    @Autowired
    private ExtSpuTagsService extSpuTagsService;

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 分页查询SPU服务标签
     */
    @ApiOperation(value = "分页查询SPU服务标签")
    @PostMapping("/query/page")
    public Response page(@RequestBody @Valid ExtSpuTagsQueryParam param) {
        try {
            QueryWrapper<ExtSpuTags> queryWrapper = new QueryWrapper<ExtSpuTags>();
            queryWrapper.lambda().eq(param.getSpuId() != null, ExtSpuTags::getSpuId, param.getSpuId())
                    .eq(param.getTagName() != null, ExtSpuTags::getTagName, param.getTagName())
                    .eq(StringUtils.isNotBlank(param.getTagValue()), ExtSpuTags::getTagValue, param.getTagValue())
                    .eq(param.getDeleted() != null, ExtSpuTags::getDeleted, param.getDeleted());
            IPage<ExtSpuTags> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = "ExtSpuTagsQueryParam{"+param.toString() + "},Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";

            return Response.data(extSpuTagsService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询SPU服务标签异常", e);
            return Response.failed("分页查询SPU服务标签异常");
        }
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 根据id查询SPU服务标签
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询SPU服务标签")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(extSpuTagsService.getById(id));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增SPU服务标签")
    public Response save(@RequestBody @Valid ExtSpuTagsAddParam param) {
        // Bean数据转换
        ExtSpuTags entity;
        try {
            entity = BeanUtils.covertType(param, ExtSpuTags.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        return Response.data(extSpuTagsService.save(entity));
    }

    @PostMapping("/saveBatch")
    @ApiOperation(value = "批量新增SPU服务标签")
    public Response saveBatch(@RequestBody List<ExtSpuTags> extSpuTags) {
        if(extSpuTags.isEmpty()) {
            return Response.data(true);
        }
        return Response.data(extSpuTagsService.saveTagsBatch(extSpuTags));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改SPU服务标签
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改SPU服务标签")
    public Response update(@RequestBody @Valid ExtSpuTagsUpdateParam param) {

        // Bean数据转换
        ExtSpuTags entity;
        try {
            entity = BeanUtils.covertType(param, ExtSpuTags.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        return Response.data(extSpuTagsService.updateById(entity));
    }

    /**
     *  删除SPU服务标签
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除SPU服务标签")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response delete(@PathVariable("id") Long id) {
        return Response.data(extSpuTagsService.deleteById(id));
    }

    /**
     * @Author:campchen
     * @Description: StringUtils.join(ids, " ") 为缓存中添加唯一KEY  如不合适可选择更好方法
     * @Date:上午 10:18 2019/5/11
     * @Param: ids
     * @return: com.hoshiicloud.common.rpc.Response
     */
    @ApiOperation(value = "根据id集合查询SPU服务标签")
    @GetMapping("/getByIds")
    public Response getByIds(@RequestParam List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.failed("id不能为空");
        }
        ids.sort(null);
        return Response.data(extSpuTagsService.getByIds(ids, StringUtils.join(ids, "")));
    }

    /**
     * 根据spuId获取标签
     *
     * @param spuId 商品SPU主键
     * @return List<ExtSpuTags>
     */
    @GetMapping("/getBySpuId/{spuId}")
    @ApiOperation(value = "根据spuId查询SPU服务标签")
    public Response<List<ExtSpuTags>> getBySpuId(@PathVariable("spuId") Long spuId) {
        return Response.data(extSpuTagsService.getBySpuId(spuId));
    }

    /**
     * 根据spuIds获取标签，并以spuId分组
     * @param spuIds 扩展spuIds
     * @return Response<Map<Long, List<ExtSpuTags>>>
     */
    @GetMapping("/getBySpuIds")
    @ApiOperation(value = "根据spuIds获取标签，并以spuId分组")
    public Response<Map<Long, List<ExtSpuTags>>> getBySpuIds(@RequestParam("spuIds") List<Long> spuIds) {
        QueryWrapper<ExtSpuTags> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(CollectionUtils.isNotEmpty(spuIds) && spuIds.size() > 0, ExtSpuTags::getSpuId, spuIds)
                             .eq(ExtSpuTags::getDeleted,0);
        List<ExtSpuTags> list = extSpuTagsService.list(queryWrapper);
        Map<Long, List<ExtSpuTags>> result = list.stream().collect(Collectors.groupingBy(ExtSpuTags::getSpuId));
        return Response.data(result);
    }

    @GetMapping("/listBySpuIds")
    @ApiOperation(value = "根据spuId集合查询SPU服务标签")
    public Response<List<ExtSpuTags>> listBySpuIds(@RequestParam("spuIds") List<Long> spuIds){
        return Response.data(extSpuTagsService.listBySpuIds(spuIds));
    }

    @GetMapping("/deleteBatchs/{extSpuId}")
    @ApiOperation(value = "根据ExtSpuId 进行批量删除")
    public Response deleteBatchs(@PathVariable("extSpuId") Long extSpuId) {
        return Response.data(extSpuTagsService.deleteBatchs(extSpuId));
    }

    @GetMapping("/removeTagsById/{id}")
    @ApiOperation(value = "根据Id删除标签信息: 物理删除")
    public Response removeTagsById(@PathVariable("id") Long id) {
        return Response.data(extSpuTagsService.removeTagsById(id));
    }


    @ApiOperation(value = "批量更新")
    @PostMapping("/updateBatch")
    public Response updateBatch(@RequestBody OmnipotentParam<ExtSpuTags> param) {
        return Response.data(extSpuTagsService.updateBatch(param));
    }

    @ApiOperation(value = "批量删除商品标签信息: 物理删除")
    @DeleteMapping("/removeBatch")
    public Response removeBatch(@RequestBody List<OmnipotentWrapper> param) {
        return Response.data(extSpuTagsService.removeBatch(param));
    }
}
